// 安全测试脚本
const http = require('k6/http');
const { check, group } = require('k6');

// 测试配置
export const options = {
  vus: 1,
  duration: '10s',
};

const BASE_URL = 'http://localhost:3003';

export default function () {
  // 测试1: SQL注入攻击防护
  group('SQL注入防护测试', function () {
    const sqlInjectionPayloads = [
      "' OR '1'='1",
      "'; DROP TABLE users; --",
      "' UNION SELECT * FROM users; --",
      "admin'--",
    ];
    
    sqlInjectionPayloads.forEach(payload => {
      // 测试登录接口
      const loginRes = http.post(`${BASE_URL}/api/users/login`, JSON.stringify({
        phone: payload,
        password: payload
      }), {
        headers: { 'Content-Type': 'application/json' },
      });
      
      // 正常的SQL注入应该被阻止或不返回敏感信息
      check(loginRes, {
        'SQL注入防护 - 登录接口': (r) => r.status !== 500,
      });
      
      // 测试账单接口
      const billsRes = http.get(`${BASE_URL}/api/bills?description=${encodeURIComponent(payload)}`, {
        headers: { 'Authorization': 'Bearer fake-token' },
      });
      
      check(billsRes, {
        'SQL注入防护 - 账单接口': (r) => r.status !== 500,
      });
    });
  });
  
  // 测试2: XSS攻击防护
  group('XSS防护测试', function () {
    const xssPayloads = [
      '<script>alert("xss")</script>',
      '"><script>alert("xss")</script>',
      '<img src=x onerror=alert("xss")>',
      'javascript:alert("xss")',
    ];
    
    xssPayloads.forEach(payload => {
      // 测试创建账单接口
      const createBillRes = http.post(`${BASE_URL}/api/bills`, JSON.stringify({
        type: 'expense',
        amount: 100,
        category_id: 1,
        description: payload,
        date: '2025-01-01'
      }), {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': 'Bearer fake-token'
        },
      });
      
      // XSS攻击应该被阻止或返回安全的内容
      check(createBillRes, {
        'XSS防护 - 创建账单接口': (r) => r.status !== 500,
      });
    });
  });
  
  // 测试3: 认证和授权测试
  group('认证和授权测试', function () {
    // 测试未认证访问受保护资源
    const billsRes = http.get(`${BASE_URL}/api/bills`);
    check(billsRes, {
      '未认证访问被拒绝': (r) => r.status === 401,
    });
    
    // 测试使用无效token访问
    const invalidTokenRes = http.get(`${BASE_URL}/api/bills`, {
      headers: { 'Authorization': 'Bearer invalid-token' },
    });
    check(invalidTokenRes, {
      '无效token访问被拒绝': (r) => r.status === 401,
    });
    
    // 测试访问不存在的资源
    const notFoundRes = http.get(`${BASE_URL}/api/nonexistent`, {
      headers: { 'Authorization': 'Bearer fake-token' },
    });
    check(notFoundRes, {
      '访问不存在资源返回404': (r) => r.status === 404,
    });
  });
  
  // 测试4: 输入验证测试
  group('输入验证测试', function () {
    // 测试账单金额边界值
    const invalidAmounts = [-100, 0, 999999999999];
    
    invalidAmounts.forEach(amount => {
      const createBillRes = http.post(`${BASE_URL}/api/bills`, JSON.stringify({
        type: 'expense',
        amount: amount,
        category_id: 1,
        description: '测试账单',
        date: '2025-01-01'
      }), {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': 'Bearer fake-token'
        },
      });
      
      const amountCheck = {};
      amountCheck[`无效金额${amount}被正确处理`] = (r) => r.status === 400 || r.status === 401;
      check(createBillRes, amountCheck);
    });
    
    // 测试日期格式验证
    const invalidDates = ['invalid-date', '2025-13-01', '2025-02-30'];
    
    invalidDates.forEach(date => {
      const createBillRes = http.post(`${BASE_URL}/api/bills`, JSON.stringify({
        type: 'expense',
        amount: 100,
        category_id: 1,
        description: '测试账单',
        date: date
      }), {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': 'Bearer fake-token'
        },
      });
      
      const dateCheck = {};
      dateCheck[`无效日期${date}被正确处理`] = (r) => r.status === 400 || r.status === 401;
      check(createBillRes, dateCheck);
    });
  });
  
  // 测试5: 速率限制测试
  group('速率限制测试', function () {
    // 快速发送多个请求测试速率限制
    for (let i = 0; i < 10; i++) {
      const res = http.get(`${BASE_URL}/api/categories`, {
        headers: { 'Authorization': 'Bearer fake-token' },
      });
      
      // 检查是否触发速率限制
      check(res, {
        '速率限制正常工作': (r) => r.status !== 429, // 429 Too Many Requests
      });
    }
  });
}